import { setTokenStorage } from '@/utils/im/token';
import userApi from "@/api/user.js";

const { miniProgram } = uni.getAccountInfoSync();

const state = {
    SDKAppID: process.env.NODE_ENV === 'production' && miniProgram.appId === 'wx238ad63939c8de76' ? 1400725153 : 1400404677,
    isSDKReady: false, // IM是否登录初始化完毕
    currentMessage: {}, // 当前通话IM消息对象
}

const mutations = {
    // 设置IM是否登录初始化完毕
    SET_ISSDKREADY(state, data) {
        state.isSDKReady = data;
        data && this.dispatch('getTotalUnreadMessageCount');
    },
    // 设置当前通话IM消息对象
    SET_CURRENTMESSAGE(state, data) {
        state.currentMessage = data
    }
}

const actions = {
    /**
     * 登录腾讯IM
    */
    loginIm({ state, dispatch }) {
        if (state.userInfo.token) {
            uni.setStorageSync(`TIM_${state.SDKAppID}_isTUIKit`, true);
            const params = {
                userID: state.userInfo.id + '', // 对应userInfo.id
                userSig: state.userInfo.tximid  // 对应userInfo.imId
            }
            setTokenStorage({ userInfo: params });
            uni.$TUIKit.login(params)
            // setTimeout(() => {
            //     dispatch("getTotalUnreadMessageCount"); // 获取未读消息
            // },500)
        }
    },
    // 更新IM用户信息
    updateMyProfile({state}) {
        let params = {
            nick: state.userInfo.userName,
            avatar: state.userInfo.headimg
        }
        uni.$TUIKit.updateMyProfile(params)
    },
    // 发送IM群消息
    sendMessage({ state, commit }, obj) {
        const { orderNo, meetingRoomNumber, password } = state.cellInfo;
        const { id, headimg, userName } = state.userInfo;
        const { action, groupID } = obj
        const msg = {
            action: action, // IM自定义类型
            data: {
                orderNo: orderNo,
                imGroupId: groupID,
                hostId: id + '', // 房主ID string
                // 呼叫列表
                imReceivers: [
                    {
                        receiverUserIcon: state.cellInfo.headimg,
                        receiverUserId: state.cellInfo.id + '',
                        receiverUserName: state.cellInfo.userName,
                    }
                ],
                meetingNum: meetingRoomNumber, // 房间号
                meetingPwd: password, // 密码
                sendUserIcon: headimg, // 发送人头像
                sendUserId: id + '', // 发送人ID string
                sendUserName: userName, // 发送名称
            },
            type: "meeting",
        };
        // 发送呼叫,设置当前通话IM消息对象
        if(action === 'evtImMsgCall'){
            commit("SET_CURRENTMESSAGE", msg);
        }else if(obj.replyMsg){ // 回复某个消息
            const { data } = obj.replyMsg
            msg.data.hostId = data.hostId
            msg.data.imReceivers = data.imReceivers
            msg.data.meetingNum = data.meetingNum
            msg.data.meetingPwd = data.meetingPwd
        }
        console.log(groupID);
        // 创建群消息
        const message = uni.$TUIKit.createTextAtMessage({
            to: groupID,
            conversationType: uni.$TUIKitTypes.CONV_GROUP,
            payload: {
                text: JSON.stringify(msg),
                atUserList: [state.cellInfo.id + ''],
            },
        });
        const options = {
            onlineUserOnly: true,
            offlinePushInfo: {
                disablePush: true,
            },
        };
        // 发送IM消息
        uni.$TUIKit.sendMessage(message, options).then((res) => {
            console.log(action, "发送IM消息", message);
            if(action === 'evtImMsgHangUp'){ // 拒接退出群组
                uni.$TUIKit.quitGroup(groupID).then(res=>{
                    console.log(res,'退出群组');
                })
            }
        });
    },
    // 解散自己是群主的群
    dissolveGroup({ state }){
        uni.$TUIKit.getGroupList().then(res=>{
            res.data.groupList.forEach(v => {
                const arr = v.groupID.split('-')
                if(arr[1] && arr[1] === state.userInfo.mobile){
                    userApi.destroyGroup({groupId: v.groupID}).then(res=>{
                        console.log(res,'删除群组成功');
                    })
                }
            });
        })
    },
    // 发送自定义群消息-发送后解散,当系统消息,避免污染会话列表
    // obj.type 注解 
    // contract 申请签约 
    // scanCode 扫码成功 
    // consult 咨询付费
    // uploadPictures 传输图片
    sendCustomMessage({ state, dispatch }, obj){
        const groupID = `${obj.type}-${state.userInfo.mobile}-${obj.toID}` // 创建群ID
        uni.$TUIKit.createGroup({
            name: groupID,
            type: uni.$TUIKitTypes.GRP_WORK,  // 临时会议群
            groupID,
            memberList: [
                {
                    userID: obj.toID + '', // string, that.cellInfo.id
                },
            ]
        }).then(() => {
            // 创建自定义群消息
            const sengData = {
                data: {
                    createTime: new Date().getTime(),
                    headimg: state.userInfo.headimg,
                    id: state.userInfo.id,
                    sex: state.userInfo.sex,
                    userName: state.userInfo.userName,
                    extension: obj.title
                },
                type: obj.type,
            }
            // 申请签约
            if(obj.type === 'contract'){
                sengData.data.description = obj.apText
                sengData.data.ap_id = obj.ap_id
            }
            // 付费咨询
            if(obj.type === 'consult'){
                sengData.data = Object.assign(sengData.data, obj.meetingData)
            }
            // 传输图片
            if(obj.type === 'uploadPictures'){
              sengData.data = Object.assign(sengData.data, {tongue: obj.tongue, face: obj.face, imgs: obj.images || []})
            }
            const msg = {
                to: groupID,
                conversationType: uni.$TUIKitTypes.CONV_GROUP,
                payload: {
                    text: JSON.stringify(sengData)
                }
            }
            const message = uni.$TUIKit.createTextAtMessage(msg)
            // 发送IM消息
            uni.$TUIKit.sendMessage(message).then(() => {
                console.log("发送自定义IM群消息", message);
                setTimeout(() => {
                    dispatch("dissolveGroup"); // 解散群组
                }, 2000);
            });
        })
    },
    // 获取单聊会话的未读总数
    getTotalUnreadMessageCount(){
      uni.$TUIKit.getConversationList({ type: uni.$TUIKitTypes.CONV_C2C }).then(res=>{
        let c2cUnreadCount = 0
        res.data.conversationList.forEach(v=>{
          if(v.conversationID !== "C2Cadministrator"){
            c2cUnreadCount += v.unreadCount
          }
        })
        console.log(c2cUnreadCount,'未读数量');
        c2cUnreadCount ? uni.showTabBarRedDot({index:1}) : uni.hideTabBarRedDot({index: 1})
      })
    }
}

export default {
    state,
    mutations,
    actions
}